import React from 'react';
import { connect } from 'dva';
import { Redirect, Link } from 'umi';
import { stringify } from 'querystring';
import PageLoading from '@/components/PageLoading';

class SecurityLayout extends React.Component {
  state = {
    isReady: false,
  };

  componentDidMount() {
    this.setState({
      isReady: true,
    });
  }
  render() {
    const { isReady } = this.state;
    const { children, loading, currentUser } = this.props; // You can replace it to your authentication rule (such as check token exists)
    // 你可以把它替换成你自己的登录认证规则（比如判断 token 是否存在）
    const isLogin = (localStorage.getItem('user') && JSON.parse(localStorage.getItem('user')).token) || (sessionStorage.getItem('user') && JSON.parse(sessionStorage.getItem('user')).token);

    if ((!isLogin && loading) || !isReady) {
      return <PageLoading />;
    }

    if (!isLogin) {
      return <Redirect to="/user/login" />
    }

    return children;
  }
}

export default connect(({ login, loading }) => ({
  currentUser: login.currentInfo,
  loading: loading.models.user,
}))(SecurityLayout);
